import axios from 'axios';
import { Message } from 'element-ui';
import router from '@/router';
function validateMockStatus(config) {
    const data = config.params ? config.params : config.data;
    return data;
}

// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 600000 // request timeout
});

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent

        config.baseURL = validateMockStatus(config);
        config.params && config.params.mock === false && delete config.params.mock;
        config.data && config.data.mock === false && delete config.data.mock;
        return config;
    },
    error => {
        console.log(error); // for debug
        return Promise.reject(error);
    }
);

// response interceptor
service.interceptors.response.use(

    response => {
        const res = response.data;
        // if the custom code is not 20000, it is judged as an error.
        if (response.status !== 200) {
            Message({
                message: res.msg || response.statusText || 'Server Error',
                type: 'error',
                duration: 5 * 1000
            });

            // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
            if (response.status === 401) {
                // to re-login
                // store.dispatch('user/login').then(() => {
                //     console.log('login success');
                // });
            }
            return Promise.reject(new Error(response.statusText || 'Error'));
        } else {
            if (
                res.ret === 0 ||
                res.ret === 'SUCCESS' ||
                res.ret === 'OK' ||
                res.code === 'SUCCESS' ||
                res.code === 'OK'
            ) {
                return res.data;
            } else {
                return Promise.reject(res);
            }
        }
    },
    error => {
        console.log(error);
        if (error.response.status === 401) {
            // store.dispatch('user/login').then(() => {
            //     console.log('login success');
            // });
            router.replace('/login');
        } else {
            // Message({
            //     message: error.message,
            //     type: 'error',
            //     duration: 5 * 1000
            // });
            return Promise.reject({ msg: error.message });
        }
    }
);

export default service;
